<template>
    <div class="dept-score-container">
        <h2>部门评分</h2>

        <!-- 部门选择器 -->
        <el-select v-model="selectedDeptId" placeholder="请选择部门" @change="handleDeptChange">
            <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
        </el-select>

        <!-- 表单提交评分 -->
        <el-form :model="scoreForm" label-width="100px" style="margin-top: 20px;">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="沟通能力">
                        <el-input-number v-model="scoreForm.communicationScore" :min="1" :max="10" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="团队协作">
                        <el-input-number v-model="scoreForm.teamworkScore" :min="1" :max="10" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="工作效率">
                        <el-input-number v-model="scoreForm.productivityScore" :min="1" :max="10" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="创新能力">
                        <el-input-number v-model="scoreForm.innovationScore" :min="1" :max="10" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="领导力">
                        <el-input-number v-model="scoreForm.leadershipScore" :min="1" :max="10" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-button type="primary" @click="submitScore">提交评分</el-button>
        </el-form>

        <!-- 雷达图 -->
        <div ref="chart" style="width: 600px; height: 400px; margin-top: 30px;"></div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage } from 'element-plus';
// 部门列表和选中部门 ID
const deptList = ref([])
const selectedDeptId = ref(null)

// 评分数据与表单
const scoreData = ref([])
const scoreForm = ref({
    communicationScore: 5,
    teamworkScore: 5,
    productivityScore: 5,
    innovationScore: 5,
    leadershipScore: 5
})

// 图表相关
const chart = ref(null)
let myChart = null // 存储 ECharts 实例，避免重复初始化

// 判断是否是有效的评分对象
function isValidScore(item) {
    return (
        item &&
        typeof item.communicationScore === 'number' &&
        typeof item.teamworkScore === 'number' &&
        typeof item.productivityScore === 'number' &&
        typeof item.innovationScore === 'number' &&
        typeof item.leadershipScore === 'number'
    )
}

// 加载部门列表
const loadDeptList = async () => {
    const res = await request.get('/dept/list', {
        params: { pageNum: 1, pageSize: 100 }
    })
    deptList.value = res.data?.records || []
}

// 加载所有评分并计算平均值
const loadAllScores = async () => {
    const res = await request.get('/dept/score')
    scoreData.value = res.data || []

    if (scoreData.value.length === 0) {
        drawChart([]) // 清空图表
        return
    }

    const validData = scoreData.value.filter(isValidScore)

    if (validData.length === 0) {
        drawChart([])
        return
    }

    const avgValues = [0, 0, 0, 0, 0]
    for (let item of validData) {
        avgValues[0] += item.communicationScore
        avgValues[1] += item.teamworkScore
        avgValues[2] += item.productivityScore
        avgValues[3] += item.innovationScore
        avgValues[4] += item.leadershipScore
    }

    const avgResult = avgValues.map(v => (v / validData.length).toFixed(2))

    drawChart([{ name: '平均分', value: avgResult }])
}

// 选择部门事件
const handleDeptChange = async (deptId) => {
    if (!deptId) return

    const res = await request.get(`/dept/score/dept/${deptId}`)

    const data = res.data ? [{
        name: deptId,
        value: [
            res.data.communicationScore,
            res.data.teamworkScore,
            res.data.productivityScore,
            res.data.innovationScore,
            res.data.leadershipScore
        ]
    }] : []

    drawChart(data)
}

// 提交评分
const submitScore = async () => {
    if (!selectedDeptId.value) {
        alert('请先选择部门')
        return
    }

    const payload = {
        deptId: selectedDeptId.value,
        ...scoreForm.value
    }

    try {
        await request.post('/dept/score', payload)
        ElMessage.success('评分提交成功！')
        await loadAllScores()

    } catch (error) {
        console.error('提交评分失败:', error)
        ElMessage.error('评分提交失败，请重试')
    }
}

// 绘制雷达图
const drawChart = (data) => {
    if (!chart.value) return

    // 销毁旧图表实例
    if (myChart) {
        myChart.dispose()
        myChart = null
    }

    // 初始化新图表
    myChart = echarts.init(chart.value)

    const indicator = [
        { name: '沟通能力', max: 10 },
        { name: '团队协作', max: 10 },
        { name: '工作效率', max: 10 },
        { name: '创新能力', max: 10 },
        { name: '领导力', max: 10 }
    ]

    myChart.setOption({
        title: {
            text: '部门评分雷达图'
        },
        tooltip: {},
        radar: {
            indicator: indicator
        },
        series: [{
            name: '评分',
            type: 'radar',
            data: data
        }]
    })
}

// 生命周期钩子
onMounted(async () => {
    await loadDeptList()
    await loadAllScores() // 已在内部调用 drawChart([...])
})
</script>

<style scoped>
.dept-score-container {
    padding: 20px;
}
</style>